package com.gitee.qdbp.general.common.web.controller.files;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.baidu.ueditor.upload.IStorageManager;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.general.common.api.files.service.IWebFileService;
import com.gitee.qdbp.tools.files.PathTools;

public class UeditorUploader implements IStorageManager {

    private IWebFileService files;

    public UeditorUploader(IWebFileService files) {
        this.files = files;
    }

    @Override
    public State saveBinaryFile(byte[] data, String rootPath, String savePath) {
        try {
            String url = files.upload(savePath, new ByteArrayInputStream(data), data.length);

            State state = new BaseState(true);
            state.putInfo("size", data.length);
            // state.putInfo( "title", targetFile.getName() );
            state.putInfo("url", url);
            state.putInfo("type", PathTools.getExtension(savePath));
            return state;
        } catch (ServiceException e) {
            return new BaseState(false, e.getMessage());
        }
    }

    @Override
    public State saveFileByInputStream(InputStream is, String rootPath, String savePath) {
        return saveFileByInputStream(is, rootPath, savePath, 0);
    }

    @Override
    public State saveFileByInputStream(InputStream is, String rootPath, String savePath, long maxSize) {
        try {
            byte[] data = toByteArray(is, maxSize);
            return saveBinaryFile(data, rootPath, savePath);
        } catch (OversizeException e) {
            return new BaseState(false, AppInfo.MAX_SIZE);
        } catch (IOException e) {
            return new BaseState(false, AppInfo.IO_ERROR);
        }
    }

    private static class OversizeException extends IOException {

        private static final long serialVersionUID = 1L;

    }

    /**
     * 将文件转为字节数组
     *
     * @param file
     * @return
     * @throws IOException
     */
    private static byte[] toByteArray(InputStream is, long maxSize) throws IOException {

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            int size = 1024;
            byte[] buffer = new byte[size];
            int index = 0;
            while ((index = is.read(buffer, 0, size)) > 0) {
                baos.write(buffer, 0, index);
                if (maxSize > 0 && baos.size() > maxSize) {
                    throw new OversizeException();
                }
            }
            return baos.toByteArray();
        }
    }
}
